/**
 * Falcon5 监控模块
 */
var Monitor = {
    config: {
        debug: false,
        ajax_url: '',
        trace_id: ''
    },

    /**
     * 初始化监控模块
     * @param {Object} config - 配置信息
     */
    init: function(config) {
        config = config || {};
        
        // 合并配置
        for (var key in config) {
            if (config.hasOwnProperty(key)) {
                this.config[key] = config[key];
            }
        }
        
        // 如果没有设置ajax_url，尝试从全局变量获取
        if (!this.config.ajax_url && window.falcon5_ajax_config && window.falcon5_ajax_config.ajax_url) {
            this.config.ajax_url = window.falcon5_ajax_config.ajax_url;
        }
        
        // 如果没有设置debug模式，尝试从全局变量获取
        if (window.falcon5_ajax_config && typeof window.falcon5_ajax_config.debug !== 'undefined') {
            this.config.debug = !!window.falcon5_ajax_config.debug;
        }
        
        this.initErrorMonitor();
        
        if (this.config.debug) {
            console.log('Falcon5 Monitor initialized with config:', this.config);
        }
    },

    /**
     * 初始化错误监控
     */
    initErrorMonitor: function() {
        var self = this;
        
        // 捕获全局错误
        window.addEventListener('error', function(event) {
            if (event.target && (event.target.tagName === 'SCRIPT' || event.target.tagName === 'LINK' || event.target.tagName === 'IMG')) {
                self.logError({
                    type: 'resource_error',
                    message: 'Failed to load ' + event.target.tagName.toLowerCase() + ': ' + (event.target.src || event.target.href),
                    filename: event.target.src || event.target.href,
                    error: event.error
                });
            } else {
                self.logError({
                    type: 'js_error',
                    message: event.message,
                    filename: event.filename,
                    lineno: event.lineno,
                    colno: event.colno,
                    error: event.error
                });
            }
            return false;
        }, true);

        // 捕获未处理的 Promise 错误
        window.addEventListener('unhandledrejection', function(event) {
            var reason = event.reason;
            var message = reason && reason.message ? reason.message : 'Promise rejection';
            
            self.logError({
                type: 'promise_error',
                message: message,
                error: reason
            });
            return false;
        });

        // 监控 Falcon5 相关的脚本加载
        var scripts = document.querySelectorAll('script[src*="falcon5"]');
        for (var i = 0; i < scripts.length; i++) {
            var script = scripts[i];
            if (!script.hasAttribute('data-monitored')) {
                script.setAttribute('data-monitored', 'true');
                script.addEventListener('error', function(event) {
                    self.logError({
                        type: 'falcon5_script_error',
                        message: 'Failed to load Falcon5 script: ' + this.src,
                        filename: this.src,
                        error: event
                    });
                });
            }
        }
    },

    /**
     * 记录错误日志
     * @param {Object} errorInfo - 错误信息对象
     */
    logError: function(errorInfo) {
        var now = new Date();
        var datetime = now.getFullYear() + '-' +
            ('0' + (now.getMonth() + 1)).slice(-2) + '-' +
            ('0' + now.getDate()).slice(-2) + ' ' +
            ('0' + now.getHours()).slice(-2) + ':' +
            ('0' + now.getMinutes()).slice(-2) + ':' +
            ('0' + now.getSeconds()).slice(-2);

        // 构建与服务器端 LogJsonFormatter 一致的日志格式
        var logData = {
            datetime: datetime,
            msg: errorInfo.message,
            level: 'error',
            module: 'falcon5-js',
            request_params: {
                url: window.location.href,
                user_agent: navigator.userAgent,
                error_type: errorInfo.type,
                filename: errorInfo.filename,
                lineno: errorInfo.lineno,
                colno: errorInfo.colno
            },
            trace_id: this.config.trace_id || '',
            uri: window.location.pathname,
            context: {
                stack: errorInfo.error && errorInfo.error.stack ? errorInfo.error.stack : '',
                type: errorInfo.type
            },
            extra: {
                browser_info: {
                    userAgent: navigator.userAgent,
                    platform: navigator.platform,
                    language: navigator.language
                }
            }
        };

        // 发送错误日志到服务器
        var xhr = new XMLHttpRequest();
        xhr.open('POST', this.config.ajax_url || window.location.href, true);
        
        // 设置请求头为 application/x-www-form-urlencoded
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.setRequestHeader('X-Requested-By', 'falcon5');

        var self = this;
        xhr.onload = function() {
            if (xhr.status !== 200) {
                if (self.config.debug) {
                    console.error('Failed to send error log:', xhr.statusText);
                }
            }
        };

        xhr.onerror = function() {
            if (self.config.debug) {
                console.error('Failed to send error log: Network error');
            }
        };

        // 构建请求数据
        var params = [];
        params.push('action=logger_save_log');
        params.push('error_data=' + encodeURIComponent(JSON.stringify(logData)));
        
        xhr.send(params.join('&'));

        // 调试模式下输出错误信息
        if (this.config.debug) {
            console.group('Falcon5 Error Log');
            console.error(errorInfo.message);
            console.dir(logData);
            console.groupEnd();
        }
    }
};

// 在页面加载完成后自动初始化
document.addEventListener('DOMContentLoaded', function() {
    // 尝试从全局配置初始化
    var config = {};
    if (window.falcon5_ajax_config) {
        config = {
            debug: window.falcon5_ajax_config.debug || false,
            ajax_url: window.falcon5_ajax_config.ajax_url || '',
            trace_id: window.falcon5_ajax_config.trace_id || ''
        };
    }
    
    Monitor.init(config);
});

// 导出模块
window.Falcon5Monitor = Monitor; 